package com.LeeCode;

/**
 * 将有序数组转化二叉搜索树
 */

public class Code108 {

    public static void main(String[] args) {

    }

    // 将有序数组转换为二叉搜索树
    public TreeNode sortedArrayToBST(int[] nums) {
        if (nums == null || nums.length == 0) return null;
        return buildBST(nums, 0, nums.length - 1);
    }

    // 递归构建BST
    private TreeNode buildBST(int[] nums, int left, int right) {
        if (left > right) return null; // 递归结束条件

        int mid = left + (right - left) / 2; // 取中间节点，防止溢出
        TreeNode node = new TreeNode(nums[mid]); // 将中间节点作为根节点

        node.left = buildBST(nums, left, mid - 1); // 构建左子树
        node.right = buildBST(nums, mid + 1, right); // 构建右子树
        return node;
    }
}
